import base64
from io import BytesIO

import cv2
import ddddocr
import pytesseract
from PIL import Image
from playwright.sync_api import Playwright, sync_playwright, expect

ocr = ddddocr.DdddOcr(show_ad=False)


# 安全解析算术表达式（示例）
def safe_eval(expr):
    allowed_chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/'}
    if all(c in allowed_chars for c in expr):
        return str(eval(expr))
    else:
        raise ValueError("Invalid expression")


def get_captcha_result():
    img = cv2.imread('temp_captcha.png', 0)
    img = cv2.medianBlur(img, 3)
    _, img = cv2.threshold(img, 1, 255, cv2.THRESH_TRUNC + cv2.THRESH_OTSU)
    cv2.imwrite('temp_captcha_2.png', img)


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("http://129.204.145.139:8088/login?redirect=%2Findex")
    page.wait_for_selector('.login-code-img')
    base64_data = page.locator('.login-code-img').get_attribute("src").split(",")
    # # 解码 Base64 数据
    image_data = base64.b64decode(base64_data[1])
    image = Image.open(BytesIO(image_data))
    image.save("temp_captcha.png")  # 保存为临时文件

    get_captcha_result()
    with Image.open('temp_captcha_2.png') as img:
        result = ocr.classification(img)  # 使用 ddddocr 识别图片中的文字
    print(f"识别结果: {result}")

    # result = safe_eval(expression)  # 例如输入 "4-3" 输出 "1"

    # print('计算结果：：', result)
    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)
